package com.atguigu.springboot.service;

import com.atguigu.springboot.mapper.DogMapper;
import com.atguigu.springboot.pojo.Dog;
import com.atguigu.springboot.utils.PageBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author  王东剑
 * Created on 26/3/2024 PM6:44
 * Package_name com.atguigu.springboot.service
 * Description
 */
@Service
public class DogServiceImpl implements DogService {
	@Autowired
	private DogMapper dogMapper;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@Override
	public PageBean<Dog> getDogList(int currentPage, int pageSize) {
		PageHelper.startPage(currentPage, pageSize);
		List<Dog> dogList = dogMapper.getDogList();
		PageInfo<Dog> dogPageInfo = new PageInfo<>(dogList);
		return new PageBean<>(currentPage, pageSize, dogPageInfo.getTotal(), dogPageInfo.getList());
	}

	@Override
	public void deleteDogById(int id) {
		dogMapper.deleteDogById(id);
		redisTemplate.delete("Dog::"+id);
	}

	@Override
	public void insertDog(Dog dog) {
		dogMapper.insertDog(dog);
	}

	@Override
	public void updateDog(Dog dog) {
		dogMapper.updateDog(dog);
		redisTemplate.delete("Dog::"+dog.getDogId());
	}

	@Override
	public Dog getDogById(int dogId) {
		long start = System.currentTimeMillis();
		StringBuilder key = new StringBuilder("Dog::" + dogId);
		Dog dog = null;
		if (redisTemplate.hasKey(key.toString())) {
			dog = (Dog) redisTemplate.opsForValue().get(key.toString());
			System.out.println("redisTemplate dog = " + dog);
		} else {
			dog = dogMapper.getDogById(dogId);
			redisTemplate.opsForValue().set(key.toString(), dog);
			System.out.println("mysql dog = " + dog);
		}
		long end = System.currentTimeMillis();
		System.out.println("耗时:"+(end-start));
		return dog;
	}
}
